// import { getUserInfo } from './utils/utils'
import config from './config'
/**
  *
  * @param {String} url 接口
  * @param {Object} data 参数
  * @param {String} method 方法
  * @param {Boolean} isHideToast 是否隐藏toast，默认为false
  */
export default async function request({
  url,
  data = {},
  method = 'GET',
  ContentType = 'application/x-www-form-urlencoded',
  isNoToken = false,
  isHideToast = false,
  isShowModal = false,
  isShowLogin = true,
  _resolve = null
}) {
  const options = {
    url,
    data,
    method,
    ContentType,
    isNoToken,
    isHideToast,
    isShowModal,
    _resolve
  }
  if (!url) {
    throw new Error('url不能为空')
  }
  // if (!isNoToken) {
  //   try {
  //     await getUserInfo(isShowLogin)
  //   } catch (e) {
  //     console.log(e)
  //     throw new Error('未授权登录')
  //   }
  // }
  const token = wx.getStorageSync('token')
  const header = {
    'Content-Type': ContentType,
  }
  if (!isNoToken && token) {
    header['Authorization'] = `Bearer ${token}`
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      data,
      method,
      header,
      success: res => {
        const { code, message } = res.data
        if (code !== 0) {
          if (code === 401) {
            console.log(401)
            const accountInfo = wx.getAccountInfoSync();
            const { appId } = accountInfo.miniProgram
            wx.login({
              success: res => {
                wx.request({
                  url: `${config.host}/wx/auth/login`,
                  method: 'POST',
                  data: { appId, code: res.code },
                  success: (res) => {
                    const { openid, token } = res.data.data
                    wx.setStorageSync('openId', openid)
                    wx.setStorageSync('token', token)
                    options._resolve = resolve
                    request(options)
                  }
                })
              }
            })
          } else {
            if (!isHideToast) {
              showToast(message)
            }
            if (isShowModal) {
              showModal(message)
            }
            reject(res.data)
          }
        } else {
          if (_resolve) {
            _resolve(res.data)
          }
          resolve(res.data)
        }
      },
      fail: err => {
        if (!isHideToast) {
          showToast(err.data.message)
        }
        console.log(url, err)
        reject(err)
      }
    })
  })
  function showToast(text) {
    wx.showToast({
      icon: 'none',
      title: text || '请求异常',
    })
  }
  function showModal(text) {
    wx.showModal({
      title: '提示',
      content: text,
      success: (res) => {
        if (res.confirm) { }
      },
      showCancel: false
    })
  }
}
